import { downloadTemplateApi } from "@/api/financialManagement/payableManagement";
import FormHook from "@/hook/formHook";
import { message } from "ant-design-vue";
import { Ref } from "vue";
import CommonHook from "@/hook/commonHook";
import { importAddFeeApi } from "@/api/financialManagement/receivable/additionalExpense";
export default function OperationHook(state: { formState: { fileList: Array<File> }; formDataRef: Ref<any>; emit: any; loading: Ref<boolean>; drawerOpts: Base.DrawerOpts }) {
  const { formState, formDataRef, emit, loading, drawerOpts } = state;
  const { resetFields, validateZhInputHandle } = FormHook({ formState });
  const { downloadFileByUrl } = CommonHook();
  const onFinish = () => {
    const { fileList } = formState;
    const formData = new FormData();
    formData.append("file", fileList[0]);
    loading.value = true;
    importAddFeeApi(formData)
      .then((res: any) => {
        const { code, data } = res;
        const { failAddCostList } = data;
        if (code === 200 && !failAddCostList.length) {
          message.success("操作成功!");
          emit("submit");
        } else {
          drawerOpts.title = `失败信息`;
          drawerOpts.width = "1200px";
          drawerOpts.component = "ErrorMessage";
          drawerOpts.passData = failAddCostList;
          drawerOpts.visible = true;
        }
      })
      .finally(() => (loading.value = false));
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };
  const resetHandle = () => {
    resetFields();
    formDataRef.value.clearValidate();
    emit("update:visible", false);
  };
  const uploadRequest = (e: any) => {
    console.log("ddd", e);
    formState.fileList = [e.file];
    e.onProgress({ percent: 100 });
  };
  // 下载模板
  const downloadTemplateHandle = () => {
    return downloadTemplateApi({ type: 4 }).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        downloadFileByUrl(data, "导入追加费用.xlsx");
      }
    });
  };

  return {
    onFinish,
    onFinishFailed,
    resetHandle,
    resetFields,
    validateZhInputHandle,
    uploadRequest,
    downloadTemplateHandle
  };
}
